import requests
import json
from utils.log_util import get_logger

logger = get_logger()

class RequestUtil:
    def __init__(self):
        self.session = requests.Session()
    
    def send_request(self, method, url, **kwargs):
        """发送HTTP请求并记录日志"""
        try:
            # 记录请求信息
            logger.info(f"请求URL: {url}")
            logger.info(f"请求方法: {method}")
            if 'headers' in kwargs:
                logger.info(f"请求头: {json.dumps(kwargs['headers'], ensure_ascii=False, indent=2)}")
            if 'params' in kwargs:
                logger.info(f"查询参数: {json.dumps(kwargs['params'], ensure_ascii=False, indent=2)}")
            if 'data' in kwargs:
                logger.info(f"请求数据: {json.dumps(kwargs['data'], ensure_ascii=False, indent=2)}")
            if 'json' in kwargs:
                logger.info(f"请求JSON: {json.dumps(kwargs['json'], ensure_ascii=False, indent=2)}")
            
            # 发送请求
            response = self.session.request(method, url, **kwargs)
            
            # 记录响应信息
            logger.info(f"响应状态码: {response.status_code}")
            try:
                response_data = response.json()
                logger.info(f"响应JSON: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
                return response_data
            except json.JSONDecodeError:
                response_text = response.text[:500] + ('...' if len(response.text) > 500 else '')
                logger.info(f"响应文本: {response_text}")
                return response.text
        except Exception as e:
            logger.error(f"请求发生异常: {str(e)}")
            raise e